<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';

// Mock数据和函数
interface MockRequest {
  requestId: number;
  vehicleId: number;
  driverId: number;
  licensePlate: string;
  driverName: string;
  requestType: string;
  description: string;
  imageUrls?: string[];
  requestTime: string;
  approvalStatus: string;
}

const mockRequests: MockRequest[] = Array.from({ length: 50 }, (_, i) => ({
  requestId: i + 1,
  vehicleId: Math.floor(Math.random() * 100) + 1,
  driverId: Math.floor(Math.random() * 50) + 1,
  licensePlate:
    ['京A12345', '京B67890', '京C11111', '京D22222', '京E33333'][
      Math.floor(Math.random() * 5)
    ] || '京A12345',
  driverName:
    ['张三', '李四', '王五', '赵六', '钱七'][Math.floor(Math.random() * 5)] ||
    '张三',
  requestType: Math.random() > 0.5 ? '维修' : '保养',
  description:
    [
      '车辆发动机异响，需要检查',
      '定期保养，更换机油和滤芯',
      '刹车系统故障，需要维修',
    ][Math.floor(Math.random() * 3)] || '车辆发动机异响，需要检查',
  imageUrls:
    Math.random() > 0.5
      ? [`https://picsum.photos/400/300?random=${i}`]
      : undefined,
  requestTime: new Date(
    Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000,
  ).toISOString(),
  approvalStatus: '待审批',
}));

const getPendingRequestsApi = async (params: any) => {
  await new Promise((resolve) => setTimeout(resolve, 300));
  const {
    page = 1,
    pageSize = 20,
    licensePlate,
    driverName,
    requestType,
    sortBy,
    sortOrder,
  } = params;

  let filtered = mockRequests.filter((req) => req.approvalStatus === '待审批');

  if (licensePlate) {
    filtered = filtered.filter((req) =>
      req.licensePlate.includes(licensePlate),
    );
  }
  if (driverName) {
    filtered = filtered.filter((req) => req.driverName.includes(driverName));
  }
  if (requestType) {
    filtered = filtered.filter((req) => req.requestType === requestType);
  }

  // 排序功能
  if (sortBy && sortOrder) {
    filtered.sort((a, b) => {
      let aVal: any = a[sortBy as keyof MockRequest];
      let bVal: any = b[sortBy as keyof MockRequest];

      // 处理时间排序
      if (sortBy === 'requestTime') {
        aVal = new Date(aVal).getTime();
        bVal = new Date(bVal).getTime();
      }

      // 处理数字排序
      if (sortBy === 'requestId') {
        aVal = Number(aVal);
        bVal = Number(bVal);
      }

      if (sortOrder === 'asc') {
        return aVal > bVal ? 1 : -1;
      } else {
        return aVal < bVal ? 1 : -1;
      }
    });
  }

  const start = (page - 1) * pageSize;
  const end = start + pageSize;

  return {
    items: filtered.slice(start, end),
    total: filtered.length,
    page: Number(page),
    pageSize: Number(pageSize),
  };
};

const getRequestDetailApi = async (requestId: number) => {
  await new Promise((resolve) => setTimeout(resolve, 200));
  const request = mockRequests.find((req) => req.requestId === requestId);
  if (!request) throw new Error('申请不存在');
  return request;
};

const approveRequestApi = async (params: any) => {
  await new Promise((resolve) => setTimeout(resolve, 200));
  const request = mockRequests.find(
    (req) => req.requestId === params.requestId,
  );
  if (request) {
    request.approvalStatus = '已批准';
  }
  return { success: true, message: '审批成功' };
};

const rejectRequestApi = async (params: any) => {
  await new Promise((resolve) => setTimeout(resolve, 200));
  const request = mockRequests.find(
    (req) => req.requestId === params.requestId,
  );
  if (request) {
    request.approvalStatus = '已驳回';
  }
  return { success: true, message: '驳回成功' };
};

const formatTime = (time: string) => {
  return new Date(time).toLocaleString('zh-CN');
};

// 申请类型选项
const requestTypeOptions = [
  { label: '维修', value: '维修' },
  { label: '保养', value: '保养' },
];

// 搜索表单
const searchForm = reactive({
  licensePlate: '',
  driverName: '',
  requestType: undefined as string | undefined,
  sortBy: undefined as string | undefined,
  sortOrder: undefined as 'asc' | 'desc' | undefined,
});

// 表格数据
const dataSource = ref<MockRequest[]>([]);
const loading = ref(false);
const pagination = ref({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showLessItems: true,
  pageSizeOptions: ['10', '20', '50', '100'],
});

// 详情弹框
const detailVisible = ref(false);
const currentRecord = ref<MockRequest | null>(null);

// 驳回弹框
const rejectVisible = ref(false);
const rejectForm = reactive({
  approvalNotes: '',
});

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.value.current,
      pageSize: pagination.value.pageSize,
      ...searchForm,
    };

    const response = await getPendingRequestsApi(params);
    dataSource.value = response.items;
    pagination.value.total = response.total;
  } catch (error) {
    console.error('获取数据失败:', error);
    // 可以使用Element Plus的Message组件来显示错误提示
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.value.current = 1;
  fetchData();
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    licensePlate: '',
    driverName: '',
    requestType: undefined,
  });
  pagination.value.current = 1;
  fetchData();
};

// 查看详情
const handleViewDetail = async (record: MockRequest) => {
  try {
    const response = await getRequestDetailApi(record.requestId);
    currentRecord.value = response;
    detailVisible.value = true;
  } catch (error) {
    console.error('获取详情失败:', error);
    // 可以使用Element Plus的Message组件来显示错误提示
  }
};

// 同意申请
const handleApprove = async (record: MockRequest) => {
  try {
    const params = {
      requestId: record.requestId,
      approvalStatus: '已批准',
    };

    await approveRequestApi(params);
    // 可以使用Element Plus的Message组件来显示成功提示
    fetchData(); // 刷新列表
  } catch (error) {
    console.error('审批失败:', error);
    // 可以使用Element Plus的Message组件来显示错误提示
  }
};

// 驳回申请
const handleReject = (record: MockRequest) => {
  currentRecord.value = record;
  rejectVisible.value = true;
  rejectForm.approvalNotes = '';
};

// 确认驳回
const handleRejectConfirm = async () => {
  if (!rejectForm.approvalNotes.trim()) {
    // 可以使用Element Plus的Message组件来显示错误提示
    return;
  }

  try {
    const params = {
      requestId: currentRecord.value!.requestId,
      approvalStatus: '已驳回',
      approvalNotes: rejectForm.approvalNotes,
    };

    await rejectRequestApi(params);
    // 可以使用Element Plus的Message组件来显示成功提示
    rejectVisible.value = false;
    fetchData(); // 刷新列表
  } catch (error) {
    console.error('驳回失败:', error);
    // 可以使用Element Plus的Message组件来显示错误提示
  }
};

// 排序处理
const handleSortChange = (sortData: any) => {
  const { prop, order } = sortData;
  searchForm.sortBy = prop;
  searchForm.sortOrder =
    order === 'ascending' ? 'asc' : (order === 'descending' ? 'desc' : undefined);
  pagination.value.current = 1;
  fetchData();
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  pagination.value.current = 1;
  fetchData();
};

// 页码变化
const handleCurrentChange = (page: number) => {
  pagination.value.current = page;
  fetchData();
};

// 页面加载
onMounted(() => {
  fetchData();
});
</script>

<template>
  <div class="audit-list">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>维保审批</h2>
      <p>管理车辆维保申请的审批流程</p>
    </div>

    <!-- 搜索表单 -->
    <el-card class="mb-3 rounded-xl border-0 shadow-lg">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item label="车牌号" prop="licensePlate">
              <el-input
                v-model="searchForm.licensePlate"
                placeholder="请输入车牌号"
                clearable
                @keyup.enter="handleSearch"
                class="w-full"
              />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item label="司机姓名" prop="driverName">
              <el-input
                v-model="searchForm.driverName"
                placeholder="请输入司机姓名"
                clearable
                @keyup.enter="handleSearch"
                class="w-full"
              />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item label="申请类型" prop="requestType">
              <el-select
                v-model="searchForm.requestType"
                placeholder="请选择申请类型"
                clearable
                class="w-full"
              >
                <el-option
                  v-for="item in requestTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item>
              <el-button type="primary" @click="handleSearch" class="size-15">
                查询
              </el-button>
              <el-button @click="handleReset" class="size-15"> 重置 </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="rounded-xl border-0 shadow-lg">
      <el-table
        v-loading="loading"
        :data="dataSource"
        class="audit-table"
        :header-cell-style="{
          background: '#f8fafc',
          color: '#374151',
          fontWeight: '600',
          borderBottom: '2px solid #e5e7eb',
        }"
        :cell-style="{ borderBottom: '1px solid #f1f5f9' }"
        style="width: 100%"
        @sort-change="handleSortChange"
      >
        <el-table-column
          prop="requestId"
          label="申请编号"
          width="100"
          align="center"
          sortable="custom"
        >
          <template #default="{ row }">
            <span class="font-medium text-gray-800">{{ row.requestId }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="licensePlate"
          label="车牌号"
          width="120"
          sortable="custom"
        >
          <template #default="{ row }">
            <span class="font-mono font-semibold text-gray-800">{{
              row.licensePlate
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="driverName"
          label="司机姓名"
          width="100"
          sortable="custom"
        >
          <template #default="{ row }">
            <span class="text-gray-700">{{ row.driverName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="requestType"
          label="申请类型"
          width="80"
          align="center"
          sortable="custom"
        >
          <template #default="{ row }">
            <el-tag
              :type="row.requestType === '维修' ? 'danger' : 'success'"
              size="small"
              class="rounded-full px-2 py-1 text-xs font-medium"
            >
              {{ row.requestType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="description"
          label="问题描述"
          min-width="200"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span class="text-gray-700">{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="requestTime"
          label="申请时间"
          width="180"
          align="center"
          sortable="custom"
        >
          <template #default="{ row }">
            <span class="text-sm text-gray-600">{{
              formatTime(row.requestTime)
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <div class="flex justify-center space-x-2">
              <el-button
                size="small"
                @click="handleViewDetail(row)"
                class="font-medium text-blue-600 hover:text-blue-800"
              >
                详情
              </el-button>
              <el-button
                size="small"
                type="success"
                @click="handleApprove(row)"
                class="font-medium text-green-600 hover:text-green-800"
              >
                同意
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleReject(row)"
                class="font-medium text-red-600 hover:text-red-800"
              >
                驳回
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="pagination.pageSizeOptions"
          layout="total, sizes, prev, pager, next, jumper"
          :background="true"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情弹框 -->
    <div v-if="detailVisible" class="modal">
      <div class="modal-content">
        <h3>申请详情</h3>
        <div v-if="currentRecord">
          <div class="detail-row">
            <span>申请编号:</span>
            <span>{{ currentRecord.requestId }}</span>
          </div>
          <div class="detail-row">
            <span>车牌号:</span>
            <span>{{ currentRecord.licensePlate }}</span>
          </div>
          <div class="detail-row">
            <span>司机姓名:</span>
            <span>{{ currentRecord.driverName }}</span>
          </div>
          <div class="detail-row">
            <span>申请类型:</span>
            <span
              :class="
                currentRecord.requestType === '维修' ? 'tag-red' : 'tag-blue'
              "
            >
              {{ currentRecord.requestType }}
            </span>
          </div>
          <div class="detail-row">
            <span>申请时间:</span>
            <span>{{ formatTime(currentRecord.requestTime) }}</span>
          </div>
          <div class="detail-row">
            <span>问题描述:</span>
            <span>{{ currentRecord.description }}</span>
          </div>
        </div>
        <button @click="detailVisible = false">关闭</button>
      </div>
    </div>

    <!-- 驳回原因弹框 -->
    <div v-if="rejectVisible" class="modal">
      <div class="modal-content">
        <h3>驳回申请</h3>
        <div>
          <label>
            驳回原因:
            <textarea
              v-model="rejectForm.approvalNotes"
              placeholder="请输入驳回原因"
              rows="4"
              maxlength="200"
            ></textarea>
          </label>
        </div>
        <div class="modal-buttons">
          <button @click="handleRejectConfirm">确认</button>
          <button @click="rejectVisible = false">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
/* 响应式优化 */
@media (max-width: 768px) {
  :deep(.el-card) {
    margin-bottom: 16px;
  }
}

.audit-list {
  min-height: 100vh;
  padding: 24px;
  background: #f9fafb;
}

.page-header {
  margin-bottom: 24px;

  h2 {
    margin: 0 0 8px;
    font-size: 24px;
    font-weight: 600;
    color: #1f2937;
  }

  p {
    margin: 0;
    font-size: 14px;
    color: #6b7280;
  }
}

/* 搜索表单样式优化 */
:deep(.search-form .el-form-item__label) {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

:deep(.el-input__wrapper) {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px 0 rgb(0 0 0 / 5%);
  transition: all 0.2s ease;
}

:deep(.el-input__wrapper:focus-within) {
  box-shadow:
    0 0 0 3px rgb(59 130 246 / 10%),
    0 2px 4px 0 rgb(0 0 0 / 5%);
}

:deep(.el-select__wrapper) {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px 0 rgb(0 0 0 / 5%);
  transition: all 0.2s ease;
}

/* 按钮样式优化 */
:deep(.el-button) {
  font-weight: 500;
  border-radius: 8px;
  transition: all 0.2s ease;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  border: none;
  box-shadow:
    0 4px 6px -1px rgb(59 130 246 / 30%),
    0 2px 4px -1px rgb(59 130 246 / 20%);
}

/* 卡片阴影效果 */
:deep(.el-card) {
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  transition: all 0.3s ease;
}

/* 表格文字样式 */
:deep(.el-table) {
  font-size: 14px;
  color: #374151;
}

:deep(.el-table th) {
  font-weight: 600;
  color: #1f2937;
  background: #f9fafb;
}

/* 操作按钮样式 */
:deep(.el-button--small) {
  padding: 6px 12px;
  font-size: 13px;
}

.data-table {
  table {
    width: 100%;
    margin-bottom: 16px;
    overflow: hidden;
    border-collapse: collapse;
    background: #fff;
    border-radius: 12px;
    box-shadow:
      0 4px 6px -1px rgb(0 0 0 / 10%),
      0 2px 4px -1px rgb(0 0 0 / 6%);
  }

  th,
  td {
    padding: 12px 8px;
    text-align: left;
    border-bottom: 1px solid #e5e7eb;
  }

  th {
    font-weight: 600;
    color: #1f2937;
    background: #f9fafb;
    border-bottom: 2px solid #e5e7eb;
  }

  td {
    color: #6b7280;
  }

  .tag-red {
    padding: 4px 12px;
    font-size: 12px;
    font-weight: 500;
    color: white;
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    border: none;
    border-radius: 9999px;
  }

  .tag-blue {
    padding: 4px 12px;
    font-size: 12px;
    font-weight: 500;
    color: white;
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
    border: none;
    border-radius: 9999px;
  }

  .action-buttons {
    display: flex;
    gap: 8px;

    button {
      padding: 6px 12px;
      font-size: 13px;
      font-weight: 500;
      cursor: pointer;
      border: none;
      border-radius: 8px;
      transition: all 0.2s ease;

      &:first-child {
        color: #374151;
        background: #f3f4f6;

        &:hover {
          background: #e5e7eb;
        }
      }

      &:nth-child(2) {
        color: white;
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        border: none;
        box-shadow:
          0 2px 4px -1px rgb(16 185 129 / 30%),
          0 1px 2px -1px rgb(16 185 129 / 20%);

        &:hover {
          background: #059669;
          transform: translateY(-1px);
        }
      }

      &.reject-btn {
        color: white;
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        border: none;
        box-shadow:
          0 2px 4px -1px rgb(239 68 68 / 30%),
          0 1px 2px -1px rgb(239 68 68 / 20%);

        &:hover {
          background: #dc2626;
          transform: translateY(-1px);
        }
      }
    }
  }

  .pagination {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 0;

    .page-controls {
      display: flex;
      gap: 8px;
      align-items: center;

      button {
        padding: 8px 12px;
        font-size: 14px;
        cursor: pointer;
        background: white;
        border: 1px solid #d1d5db;
        border-radius: 8px;
        transition: all 0.2s ease;

        &:disabled {
          cursor: not-allowed;
          opacity: 0.5;
        }

        &:hover:not(:disabled) {
          background: #f9fafb;
          border-color: #9ca3af;
        }
      }
    }
  }
}

.modal {
  position: fixed;
  inset: 0;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgb(0 0 0 / 50%);

  .modal-content {
    width: 90%;
    max-width: 600px;
    max-height: 80vh;
    padding: 24px;
    overflow-y: auto;
    background: white;
    border-radius: 12px;
    box-shadow:
      0 20px 25px -5px rgb(0 0 0 / 10%),
      0 8px 10px -6px rgb(0 0 0 / 6%);

    h3 {
      margin: 0 0 16px;
      font-size: 18px;
      font-weight: 600;
      color: #1f2937;
    }

    .detail-row {
      display: flex;
      justify-content: space-between;
      padding-bottom: 12px;
      margin-bottom: 12px;
      border-bottom: 1px solid #e5e7eb;

      span:first-child {
        font-weight: 500;
        color: #374151;
      }

      span:last-child {
        color: #6b7280;
      }
    }

    label {
      display: block;
      margin-bottom: 8px;
      font-weight: 500;
      color: #374151;

      textarea {
        width: 100%;
        padding: 12px;
        font-size: 14px;
        resize: vertical;
        border: 1px solid #d1d5db;
        border-radius: 8px;
        transition: all 0.2s ease;

        &:focus {
          outline: none;
          border-color: #3b82f6;
          box-shadow: 0 0 0 3px rgb(59 130 246 / 10%);
        }
      }
    }

    .modal-buttons {
      display: flex;
      gap: 12px;
      justify-content: flex-end;
      margin-top: 24px;

      button {
        padding: 10px 20px;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        border: none;
        border-radius: 8px;
        transition: all 0.2s ease;

        &:first-child {
          color: white;
          background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
          border: none;
          box-shadow:
            0 4px 6px -1px rgb(59 130 246 / 30%),
            0 2px 4px -1px rgb(59 130 246 / 20%);

          &:hover {
            background: #1d4ed8;
            transform: translateY(-1px);
          }
        }

        &:last-child {
          color: #374151;
          background: #f3f4f6;
          border: 1px solid #d1d5db;

          &:hover {
            background: #e5e7eb;
          }
        }
      }
    }

    button {
      padding: 10px 20px;
      margin-top: 24px;
      font-size: 14px;
      font-weight: 500;
      color: white;
      cursor: pointer;
      background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
      border: none;
      border-radius: 8px;
      box-shadow:
        0 4px 6px -1px rgb(59 130 246 / 30%),
        0 2px 4px -1px rgb(59 130 246 / 20%);

      &:hover {
        background: #1d4ed8;
        transform: translateY(-1px);
      }
    }
  }
}
</style>
